package com.jhinwins.equipmenteb.equipmentebserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jhinwins.equipmenteb.equipmentebserver.entity.*;
import com.jhinwins.equipmenteb.equipmentebserver.service.ProductService;
import com.jhinwins.equipmenteb.equipmentebserver.utils.RespUtils;
import com.jhinwins.equipmenteb.equipmentebserver.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("products")
public class ProductController {
    private ProductService productService;
    private ResourceLoader resourceLoader;

    @Value("${server.pics.dir}")
    private String picDir;
    @Value("${server.pics.saveDir}")
    private String picSaveDir;

    @Autowired
    public ProductController(ProductService productService, ResourceLoader resourceLoader) {
        this.productService = productService;
        this.resourceLoader = resourceLoader;
    }

    /**
     * 首页界面数据
     */
    @GetMapping("index")
    public JSONObject indexDatas() {
        return RespUtils.createSucResp(productService.getIndexDatas());
    }

    /**
     * 栏目页数据
     */
    @GetMapping("floor")
    public JSONObject floorDatas(@RequestParam(name = "floorid", defaultValue = "0", required = false) Long floorid,
                                 @RequestParam(name = "keyword", defaultValue = "", required = false) String keyword,
                                 @RequestParam(name = "pageIndex", defaultValue = "0", required = false) Integer pageIndex,
                                 @RequestParam(name = "pageSize", defaultValue = "30", required = false) Integer pageSize) {
        return RespUtils.createSucResp(productService.getFloorDatas(floorid, keyword, pageIndex, pageSize));
    }

    /**
     * 商品数据
     */
    @GetMapping("product")
    public JSONObject productDatas(@RequestParam(name = "productid", defaultValue = "") Long productid) {
        return RespUtils.createSucResp(productService.getProductDatas(productid));
    }

    @PostMapping("addproduct")
    public JSONObject addProduct(@RequestBody String data) {
        JSONObject params = JSON.parseObject(data);
        ProductBean productBean = new ProductBean();
        productBean.setName(params.getString("productName"));
        productBean.setShortDesc(params.getString("productDesc"));

        //图片
        try {
            ArrayList<ProductImgBean> productImgBeans = new ArrayList<>();
            for (String picName : params.getJSONArray("productImgs").toJavaList(String.class)) {
                ProductImgBean productImgBean = new ProductImgBean();
                productImgBean.setPicDir(picDir);
                productImgBean.setImgUrl(picName);
                productImgBean.setAlt(picName);
                productImgBeans.add(productImgBean);
            }
            productBean.setProductImgBeans(productImgBeans);
        } catch (Exception ignored) {
        }
        //商品介绍
        try {
            String productIntroduceUrl = params.getString("productIntroduce");
            ProductImgBean productIntroduce = new ProductImgBean();
            productIntroduce.setPicDir(picDir);
            productIntroduce.setImgUrl(productIntroduceUrl);
            productBean.setProductIntroduce(productIntroduce);
        } catch (Exception ignored) {
        }

        //类型
        ProductTypeBean productTypeBean = new ProductTypeBean();
        productTypeBean.setId(params.getLong("productTypeid"));
        productBean.setProductTypeBean(productTypeBean);

        //规格
        for (Object productSpec : params.getJSONArray("productSpec")) {
            SpecificationBean specificationBean = new SpecificationBean();
            JSONObject proSpec = (JSONObject) productSpec;

            specificationBean.setSpecificationName(proSpec.getString("pub_name"));
            specificationBean.setStateName(proSpec.getString("pri_name"));

            for (Object value : proSpec.getJSONArray("values")) {
                JSONObject valueItem = (JSONObject) value;
                SpecValueBean specValueBean = new SpecValueBean();
                specValueBean.setName(valueItem.getString("name"));
                specValueBean.setValue(valueItem.getString("value"));
                specificationBean.getValues().add(specValueBean);
            }

            productBean.getSpecificationBeans().add(specificationBean);
        }
        return RespUtils.createSucResp(productService.addProduct(productBean));
    }

    /**
     * 获取所有的商品类型
     */
    @GetMapping("alltypes")
    public JSONObject getAllType() {
        return RespUtils.createSucResp(productService.allTypes());
    }

    /**
     * 添加库存
     */
    @PostMapping("addinventory")
    public JSONObject addInventory(@RequestBody String data) {
        JSONObject params = JSON.parseObject(data);
        InventoryBean inventoryBean = new InventoryBean();
        inventoryBean.setCount(params.getInteger("count"));
        inventoryBean.setPrice(params.getDouble("price"));

        ProductBean productBean = new ProductBean();
        productBean.setId(params.getLong("productid"));
        inventoryBean.setProductBean(productBean);

        //所选规格
        Map<SpecificationBean, SpecValueBean> specCfg = new HashMap<>();
        JSONObject selectSpec = params.getJSONObject("selectSpec");
        for (String specId : selectSpec.keySet()) {
            SpecificationBean specificationBean = new SpecificationBean();
            specificationBean.setId(Long.parseLong(specId));
            SpecValueBean specValueBean = new SpecValueBean();
            specValueBean.setId(selectSpec.getLong(specId));
            specCfg.put(specificationBean, specValueBean);
        }
        inventoryBean.setSpecCfg(specCfg);

        return RespUtils.createSucResp(productService.addInventory(inventoryBean));
    }


    /**
     * 添加到购物车
     */
    @PostMapping("addtocart")
    public JSONObject addToCart(@RequestBody String data) {

        if (UserUtils.curUser == null) {
            return RespUtils.createResp(RespUtils.UN_LOGIN);
        }

        JSONObject params = JSON.parseObject(data);
        Long productId = params.getLong("productId");
        JSONObject specifications = params.getJSONObject("specifications");
        InventoryBean inventoryBeanExa = new InventoryBean();
        inventoryBeanExa.setProductBean(new ProductBean(productId));
        HashMap<SpecificationBean, SpecValueBean> specValueBeanMap = new HashMap<>();
        for (String spec_id : specifications.keySet()) {
            SpecificationBean specificationBean = new SpecificationBean(Long.parseLong(spec_id));
            SpecValueBean specValueBean = new SpecValueBean(specifications.getLong(spec_id));
            specValueBeanMap.put(specificationBean, specValueBean);
        }

        inventoryBeanExa.setSpecCfg(specValueBeanMap);

        return RespUtils.createSucResp(productService.addToCart(new ProductBean(productId), specValueBeanMap, params.getInteger("tenancy"), params.getInteger("count")));
    }

    /**
     * 图片上传
     */
    @PostMapping("upload")
    public JSONObject uploadPic(@RequestParam("file") MultipartFile file, @RequestParam("cusName") String cusName) {

        if (file.isEmpty()) {
            System.out.println("file is empty");
        }
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(picSaveDir + file.getOriginalFilename());
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return RespUtils.createSucResp();
    }

    /**
     * 获取图片
     */
    @GetMapping("getPic")
    public ResponseEntity<?> getPic(String picName) {
        return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(picSaveDir, picName).toString()));
    }
}